import { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, ScrollView, Image } from '@tarojs/components'
import { AtNoticebar, AtButton, AtMessage } from 'taro-ui'
import { connect } from 'react-redux'
import { carInfo } from '@/store/car/action-loading'
import NoCar from './no-car'
import './index.scss'
import classnames from 'classnames'
import CarSkeleton from './skeleton'
import Iconfont from '@/components/Iconfont'
import qs from 'qs'
import { fetchSetDefault, fetchDel, queryUserCarInfo } from '@/api/car'

type State = {
  loadDone: boolean
  list: Array<any>
  max: number
  page: number
}
@connect<any>(({ car }) => ({ car }), _dispatch => ({
  dispatchFetchList(val) {
    return _dispatch(carInfo(val))
  }
}))
export default class CarList extends Component<any, State> {

  constructor (props) {
    super(props)
    this.state = {
      loadDone: false,
      list: [],
      max: -1,
      page: 1
    }
  }

  componentDidMount() {
		console.log('this',this)
    this.getList()
    this.queryUserCarInfo()
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const {
      list
    } = nextProps.car.carInfo
    this.setState({
      list
    })
  }

  // 查询用户汽车最大数量
  async queryUserCarInfo() {
    queryUserCarInfo().then(res => {
      let { max } = res.data.data
      console.log('max', max)
      this.setState({
        max
      })
    })
  }
  getList() {
    const { dispatchFetchList, car: { carInfo: { list } } } = this.props
    const { page } = this.state

    dispatchFetchList({ page, list }).then(res => {
      const data = res.list
      this.setState({
        loadDone: true,
        list: data,
      })
    })
  }


  handleAddCar() {
    Taro.navigateTo({
      url: `/pages/car/add/index?type=1`
    })
  }
  /**
   * 删除车辆
   * @param item
   */
  async handleDelCarModel(item) {
    Taro.showModal({
      title: '温馨提示',
      content: '删除车型后，车型数据将不再保留，您确认删除吗？',
      cancelText: '删除',
      cancelColor: '#999999',
      confirmText: '我再想想',
      confirmColor: '#12b3ff',
    }).then(async res => {
			console.log('res---res',res)
      if (!res.confirm) {
        try {
          let res = await fetchDel(item.id)
          if (!res.data.success) throw Error('删除车型失败，请稍后重试')
          Taro.atMessage({
            'message': '已删除',
            'type': 'success'
          })
          this.getList()
        } catch (error) {
          Taro.atMessage({
            'message': `${error.message}`,
            'type': 'error',
          })
        }
      }
    })
  }
  /**
   * 设置默认车辆
   * @param item
   */
  async handleSetDefaultCar(item) {
    if (item.isDefault === 1) return
    Taro.vibrateShort()
    try {
      let res = await fetchSetDefault(item.id)
      if (!res.data.success) throw Error('设置默认车辆失败请稍后重试')
      Taro.atMessage({
        'message': `已将车牌${item.carLicense}设置为默认车辆`,
        'type': 'success'
      })
      this.getList()
      // this.props.event.trigger('refresh')
    } catch (error) {
      Taro.atMessage({
        'message': `${error.message}`,
        'type': 'error',
      })
    }
    Taro.navigateBack({
      delta: 1
    })
  }
  /**
   * 更新车辆
   * @param item
   */
  handleUpdate(item) {
    let CarModelFullName = `${item.brandName} - ${item.seriesName} - ${item.modelName}`
    Taro.navigateTo({
      url: `/pages/car/add/index?${qs.stringify({
        type: 2,
        brandId: item.brandId,
        modelId: item.modelId,
        seriesId: item.seriesId,
        carModelFullName: CarModelFullName,
        carLicense: item.carLicense,
        isDefault: item.isDefault,
        id: item.id,
        brandName: item.brandName,
        seriesName: item.seriesName,
        modelName: item.modelName,
        jekunModelCode: item.jekunModelCode
      })}`
    })
  }

  loadingData() {
    const { car: { carInfo } } = this.props
    const { page } = this.state
    if (carInfo && carInfo.list && carInfo.list.length > 0) {
      let condition = Number(carInfo.list.length) == 50 * Number(page)
      if (condition) {
        this.setState({
          page: page + 1
        }, () => {
          this.getList()
        })
      }
    }
  }

  render() {
    const { loadDone, list, max } = this.state
    const scrollStyle = {
      height: 'calc(100vh - 206rpx)'
    }
    let carListView = list.length>0 ? <View className='car-list-item-wrap'>
      <ScrollView className='car-list-item' enableBackToTop scrollY lowerThreshold={200} onScrollToLower={() => this.loadingData()} style={scrollStyle}>
        {list.map((post, index) =>
          <View key={'key' + index} className='car-item flex-column-self'>
            <View className='at-row info-wrap'>
              <View className='head-url'>
                <Image className='car-brand' lazyLoad mode='aspectFit' src={post.brandLogoUrl} />
              </View>
              <View className='content at-col flex-column-self'>
                <View className='flex-row license-wrap'>
                  <View className={
                    classnames('license', {
                      'license-green-bg': post.isNewEnergy === 1,
                      'license-blue-bg': post.isNewEnergy === 0
                    })
                  }
                  >
                    {post.licenseProvince}{post.licenseLetter}·{post.licenseNumber}
                  </View>
                  {post.isCertified ? <View className='tab'>已认证</View> : null}
                </View>
                <View className='desc'>{post.seriesName} - {post.modelName}</View>
              </View>
            </View>
            <View className='action-wrap at-row at-row__align--center'>
              <View className='left at-col flex-row'>
                {!post.isDefault ? <View onClick={this.handleSetDefaultCar.bind(this, post)} className='radio-icon'></View> : null}
                {post.isDefault ? <View><Iconfont size='44' color='#12b3ff' name='icon-gouxuan-gouxuanxuanzhong' /></View> : null}
                {post.isDefault === 1 ?
                  <View className='text'>已设为默认</View> :
                  <View className='text' onClick={this.handleSetDefaultCar.bind(this, post)}>设为默认车辆</View>
                }
              </View>
              <View className='flex-row'>
                <AtButton className="del-btn" onClick={this.handleDelCarModel.bind(this, post)} type='secondary' size='small'>删除</AtButton>
                <AtButton className="edit-btn" type='secondary' size='small' onClick={this.handleUpdate.bind(this, post)}>编辑</AtButton>
              </View>
            </View>
          </View>
        )}
      </ScrollView>
      <AtMessage />
    </View> : <NoCar />

    return (
      <View className='car-list'>
        {!loadDone && <CarSkeleton />}
        {
          loadDone && (
            <View>
              <AtNoticebar icon='alert-circle'>
                添加爱车信息能为您精准匹配保养服务和配件
              </AtNoticebar>
              {carListView}
              {
                list.length>0 && (list.length == max || list.length > max) && max != -1 ? (
                  <View className="btn-tips">
                    目前车库最多放{max}辆车，请先删除后再添加
                  </View>
                ) : (
                  <View className='btn'>
                    <AtButton className="submit-btn" onClick={this.handleAddCar.bind(this)} type='primary'>添加爱车</AtButton>
                  </View>
                )
              }
            </View>
          )
        }
      </View>
    )
  }
}
